package com.java110.mall.shop.cmd.shopSms;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.CmdContextUtils;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.utils.cache.CommonCache;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.cache.UrlCache;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;

import java.math.BigDecimal;

/**
 * 计算短信金额
 */
@Java110Cmd(serviceCode = "shopSms.computeSmsAmount")
public class ComputeSmsAmountCmd extends Cmd {
    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        Assert.hasKeyAndValue(reqJson, "shopId", "shopId不能为空");
        Assert.hasKeyAndValue(reqJson, "buyCount", "buyCount不能为空");

    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        String smsPrice = MappingCache.getValue("SMS_DOMAIN", "SHOP_SMS_PRICE");
        if (StringUtil.isEmpty(smsPrice)) {
            smsPrice = "0.1";
        }
        BigDecimal amount = new BigDecimal(smsPrice);

        amount = amount.multiply(new BigDecimal(reqJson.getString("buyCount"))).setScale(2, BigDecimal.ROUND_HALF_UP);
        String createUserId = CmdContextUtils.getUserId(context);
        String shopId = reqJson.getString("shopId");
        String token = GenerateCodeFactory.getUUID();

        JSONObject payData = new JSONObject();
        payData.put("shopId", shopId);
        payData.put("business", "shopBuySms");
        payData.put("createUserId", createUserId);
        payData.put("money", amount.doubleValue());
        payData.put("buyCount", reqJson.getString("buyCount"));
        CommonCache.setValue("nativeQrcodePayment_" + token, payData.toJSONString(), CommonCache.PAY_DEFAULT_EXPIRE_TIME);
        JSONObject data = new JSONObject();
        String mallAppUrl = UrlCache.getMallAppUrl();
        mallAppUrl = mallAppUrl.endsWith("/") ? mallAppUrl : (mallAppUrl + "/");
        data.put("qrCode", mallAppUrl + "#/pages/order/qrCodeCashier?qrToken=" + token);
        data.put("amount", amount);
        data.put("remark", "微信扫码支付，需要支付金额为" + amount);
        context.setResponseEntity(ResultVo.createResponseEntity(data));

    }
}
